3. ヒストグラム

3.1. 概要

ヒストグラムとは,例えば下図のように,

3.2. Plotlyによる作図方法

Plotlyでは,plotly.express.histogram()でヒストグラムを作成可能です.

import plotly.express as px
fig = px.histogram(df, x='col_x')

上記の例では,dfcol_x列をX軸,その度数をY軸に取ったヒストグラムのオブジェクトfigを作成します.また,

fig = px.histogram(df, x='col_x', cumulative=True)

cumulative=Trueオプションを指定することで,累積ヒストグラムを作図可能です.更に,

fig = px.histogram(df, x='col_x', color='col_stack', barmode='stack')

barmode='stack'を指定することで,col_stack列に関する積み上げヒストグラムを作図可能です. もちろん,cumulativeとの組み合わせて使うこともできます.

3.3. MADB Labを用いた作図例

3.3.1. 下準備

import pandas as pd
import plotly.express as px

import warnings
warnings.filterwarnings('ignore')
# 前処理の結果,以下に分析対象ファイルが格納されていることを想定
PATH_DATA = '../../data/preprocess/out/episodes.csv'
# Jupyter Book用のPlotlyのrenderer
RENDERER = 'plotly_mimetype+notebook'
def show_fig(fig):
    """Jupyter Bookでも表示可能なようRendererを指定"""
    fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
    fig.show(renderer=RENDERER)
df = pd.read_csv(PATH_DATA)

3.3.2. 各話のページ数の分布

fig = px.histogram(
    df, x='pages', title='各話のページ数')
show_fig(fig)

これでは少し見づらいので,表示範囲をfig.update_xaxis()で変更します.

fig.update_xaxes(range=[0, 50])
show_fig(fig)

cumulative=Trueオプションを指定することで,累積分布を作図することもできます.

fig = px.histogram(
    df, x='pages', title='各話のページ数', cumulative=True)
fig.update_xaxes(range=[0, 50])
show_fig(fig)

3.3.3. 雑誌別の各話のページ数の分布

df = df.sort_values('mcname', ignore_index=True)
fig = px.histogram(
    df, x='pages', color='mcname', barmode='stack',
    color_discrete_sequence= px.colors.diverging.Portland,
    title='雑誌別の各話のページ数')
fig.update_xaxes(range=[0, 50])
show_fig(fig)
for mcname in sorted(df['mcname'].unique()):
    df_tmp = df[df['mcname']==mcname].reset_index(drop=True)
    fig = px.histogram(
        df_tmp, x='pages', title=f'{mcname}の各話のページ数',)
    fig.update_xaxes(range=[0, 50])
    show_fig(fig)